<template>
  <div class="container">
    <div class="head-top">
      <span>{{nowAccount.name}}</span>
      <img
        class="right"
        @click="popupVisible=!popupVisible"
        src="static/img/wallet2.png"
        width="100%"
        height="100%"
      />
      <img
        class="left"
        @click="$router.back()"
        src="static/img/return.png"
        width="100%"
        height="100%"
      />
    </div>
    <div style="position: absolute;left:46%;top:30%" v-if="isLoading">
      <van-loading type="spinner" color="#65686C" />
    </div>
    <div style="overflow-x:hidden;height: 93%;">
       <div id="tranList">
        <div
          class="tran"
         v-for="(tran,index) in ethTranList"
          @click="$router.push({name:'MyTransactionInfo',params:{tran:tran}})"
          :key="index"
        >
          <div class="left">
            <img v-if="!tran.get" src="static/img/out.png" />
            <img v-if="tran.get" src="static/img/enter.png" />
            <div>
              <div class="add">{{tran.fromAddress==currentAccount.address.toLowerCase()?tran.toAddress:tran.fromAddress}}</div>
              <div class="date">{{tran.date}}</div>
            </div>
          </div>
          <div class="right">
            <div
              class="out"
              v-if="!tran.get"
            >-{{tran.value}} ether</div>
            <div
              class="enter"
              v-if="tran.get"
            >{{tran.value}} ether</div>
            <div class="out" v-if="tran.error">交易失败</div>
            <div class="enter" v-if="tran.pending">等待打包</div>
          </div>
        </div>
      </div>
    </div>

    <mt-popup
      id="enterPopul"
      v-model="popupVisible"
      popup-transition="popup-fade"
      style="width: 60%;border-radius: .5rem;padding: 0px 5%"
    >
      <h3
        style="margin:0rem;padding: .3rem 0rem; text-align: center;border-bottom: 0.5px solid rgba(0,0,0,0.5)"
      >切换钱包</h3>

      <div class="ethbox" v-if="wallet.length>0">
        <div class="ethWallet">
          <div v-for="account,index in wallet">
            <div
              class="wallet"
              :class="{active:index==ethSwitchIndex}"
              @click="toggleWallet(2,index)"
            >
              <img :src="account.img" alt />&nbsp;&nbsp;
              <span>{{account.name}}</span>
            </div>
          </div>
        </div>
      </div>
    </mt-popup>
  </div>
</template>


<script>
import { Loading } from "vant";
//
import { mapGetters, mapActions } from "vuex";
import { etherscanAK } from "../../service/eth/config";
import axios from "axios";

// import  accountUtils from '../../service/accountUtils'

export default {
  components: { Loading },
  data() {
    return {
      nowAccount: "",
      ethSwitchIndex: "",
      popupVisible: false,
      isLoading: true,
      ethTranList: [],
      chartsData: {},
    };
  },
  computed: {
    ...mapGetters(["currentAccount", "wallet", "accountIndex", "ethBaseNet"]),
  },
  created() {
    let _this = this;

    this.nowAccount = this.currentAccount;
    this.ethSwitchIndex = this.accountIndex;
    this.ethTranList = this.nowAccount.allTransactionList.reverse();

    // if(this.currentAccount.allTransactionList&&this.currentAccount.allTransactionList[0]){
    //   let list= [].concat(this.currentAccount.allTransactionList)
    //   this.tranList = list.reverse()
    //
    // }
  },
  methods: {
    ...mapActions(["setWallet", "set", "setAccountIndex"]),
    convertBigNumber(param) {
      let strParam = String(param);
      let flag = /e/.test(strParam);
      if (!flag) return param;

      // 指数符号 true: 正，false: 负
      let sysbol = true;
      if (/e-/.test(strParam)) {
        sysbol = false;
      }
      // 指数
      let index = Number(strParam.match(/\d+$/)[0]);
      // 基数
      let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, "");

      if (sysbol) {
        return basis.padEnd(index + 1, 0);
      } else {
        return basis.padStart(index + basis.length, 0).replace(/^0/, "0.");
      }
    },
    formatDateTime(inputTime) {
      var date = new Date(inputTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },
    getEthTransactionList(account, index) {
      //  let oldTranList = [].concat(this.currentAccount.allTransactionList);

      let _this = this;

      let date = (new Date().getTime() + "").substring(0, 10);

      let url =
        "http://api-cn.etherscan.com/api?module=account&action=txlist&address=" +
        account.address +
        "&startblock=0&endblock=99999999&sort=asc&apikey=" +
        etherscanAK;

      axios.get(url).then((resp) => {
        console.log(resp);
        let transactionList = [];
        if (resp.status == "200") {
          let list = resp.data.result;

          //  if (list.length > oldTranList.length) {
          for (let i = 0; i < list.length; i++) {
            let obj = list[i];
            if (obj.value == 0) {
              continue;
            }

            console.log(list);
            let tran = {
              fromAddress: obj.contractAddress ? obj.contractAddress : obj.from,
              toAddress: obj.contractAddress ? obj.contractAddress : obj.to,
              img: "",
              name: "ether",
              error: false,
              get: false,
              txhash: obj.hash,
              blockNumber: obj.blockNumber,
              blockHash: obj.blockHash,
              date: this.formatDateTime(obj.timeStamp),
              timeStamp: obj.timeStamp,
              value: parseFloat(
                parseFloat(
                  this.global.web3.utils.fromWei(obj.value, "ether")
                ).toFixed(8)
              ),
              wei: obj.value,
              gasMoney: "",
              input: "",
              pending: false,
            };

            let gasMoney = this.global.web3.utils.fromWei(
              parseInt(obj.gasUsed) * parseInt(obj.gasPrice) + "",
              "ether"
            );

            tran.gasMoney = gasMoney;
            if (obj.input != "0x") {
              tran.input = obj.input.toString();
            }

            if (obj.txreceipt_status == "0") {
              tran.error = true;
              tran.img = "static/img/error.png";
            } else if (obj.contractAddress) {
              tran.img = "static/img/contract.png";
            } else if (obj.from == account.address.toLowerCase() && obj.to) {
              tran.img = "static/img/to2.png";
            } else if (obj.from != account.address.toLowerCase()) {
              tran.get = true;
              tran.img = "static/img/from.png";
            }

            let timeStamp = parseInt(obj.timeStamp);
            let subtract = date - timeStamp;
            if (subtract < 1) {
              tran.date = "1秒前";
            } else if (subtract < 60) {
              tran.date = subtract.toFixed(0) + "秒前";
            } else if (subtract < 60 * 60) {
              tran.date = (subtract / 60).toFixed(0) + " 分前";
            } else if (subtract > 60 * 60 && subtract < 60 * 60 * 24) {
              tran.date = (subtract / 60 / 60).toFixed(0) + " 小时前";
            } else if (
              subtract > 60 * 60 * 24 &&
              subtract < 60 * 60 * 24 * 30
            ) {
              tran.date = (subtract / 60 / 60 / 24).toFixed(0) + " 日前";
            } else {
              tran.date = this.formatDateTime(timeStamp * 1000);
            }
            transactionList.push(tran);
            console.log(tran);
          }
          account.allTransactionList = transactionList;
          _this.wallet[index] = account;

          _this.setWallet(_this.wallet);
          _this.ethTranList = [].concat(transactionList).reverse();
        }
        _this.isLoading = false;
        //  }
      });
    },
    //将科学计数法转换为小数
    toNonExponential(num) {
      var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
      return num.toFixed(Math.max(0, (m[1] || "").length - m[2]));
    },
    toggleWallet(type, index) {
      this.popupVisible = false;
      this.isLoading = true;

      let ethAccount = this.wallet[index];
      this.nowAccount = ethAccount;
      this.ethSwitchIndex = index;
      this.getEthTransactionList(ethAccount, index);

      // if(index!=this.accountIndex){
      //   this.isLoading=true
      //   this.popupVisible=!this.popupVisible
      //   this.setAccountIndex(index)
      //   let account=this.wallet[index];
      //   this.getEthTransactionList(account)
      // }
    },
  },
  async mounted() {
    this.getEthTransactionList(this.currentAccount);
  },

  watch: {
    tranList(newvalue, oldvalue) {},
  },
};
</script>
<style lang="less" scoped>
@import url("../../assets/css/myTransactionHistory.less");
</style>

